package org.btik.light.meta.base.type;

import org.btik.light.meta.base.Command;
import org.btik.light.meta.event.DevEvent;
import org.btik.light.meta.event.DevEventListener;
import org.btik.light.meta.event.cmd.DefaultCmd;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lustre
 * @version 1.0
 * @since 2021/5/15 12:37
 * id发生器
 */

public class CmdIdGenerator implements DevCmdBuilder, DevEventListener {
    private final static ConcurrentHashMap<String, Integer> CMD_IDS = new ConcurrentHashMap<>();

    @Override
    public void buildCmd(Command command) {
        if (command instanceof DefaultCmd) {
            String target = command.getTarget();
            Integer compute = CMD_IDS.compute(target, (k, v) -> v == null ? 0 : ++v);
            ((DefaultCmd) command).setCmdId(compute);
        }
    }


    @Override
    public void onConnected(DevEvent devEvent) {

    }

    @Override
    public void onDisConnected(DevEvent devEvent) {
        CMD_IDS.remove(devEvent.getDev());
    }
}
